/*
 * 文件名：SynchronizationController.java
 * 版权：Copyright by www.ysepay.com
 * 修改人：mosx
 * 修改时间 2016年7月22日
 */

package com.yspay.sample.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.yspay.sample.ApipaySubmit;
import com.yspay.sample.intercepter.HttpReqRespHolder;
import com.yspay.sample.request.SynchronizationRequest;

@Controller
public class SynchronizationController {
	private Logger log = LoggerFactory.getLogger(SynchronizationController.class);
	@Value("${pay.parameter.path.ysepay.public.cert}")
	private String path_ysepay_public_cert;

	@RequestMapping(value = "/demo/webSynReturn.do", params = "method=synchronizationReturn")
	public ModelAndView synchronizationReturn(SynchronizationRequest req) {

		HttpServletRequest request = HttpReqRespHolder.getHttpServletRequest();

		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		log.info("同步通知发起地址:" + ip);
		String trade_status = req.getTrade_status();

		Map<String, String> param = new HashMap<String, String>();
		param.put("out_trade_no", req.getOut_trade_no());
		param.put("total_amount", req.getTotal_amount());
		param.put("trade_no", req.getTrade_no());
		param.put("trade_status", trade_status);
		param.put("account_date", req.getAccount_date());
		param.put("notify_type", req.getNotify_type());
		param.put("notify_time", req.getNotify_time());
		param.put("sign_type", req.getSign_type());
		param.put("extra_common_param", req.getExtra_common_param());
		param.put("sign", req.getSign());

		boolean paramsResult = ApipaySubmit.verifySign(request, param,
				path_ysepay_public_cert);
		ModelMap model = new ModelMap();
		if (paramsResult) {
			log.info("同步通知验证签名成功");
			if (trade_status.equals("TRADE_FINISHED")
					|| trade_status.equals("TRADE_SUCCESS")) {
				model.put("returnMsg", "订单支付成功");
			} else {
				model.put("returnMsg", "订单支付失败");
			}

		} else {
			log.info("同步通知验证签名失败, 订单状态未知，请发起查询订单请求，查询交易状态");
			model.put("returnMsg", "同步通知验证签名失败, 订单状态未知，请发起查询订单请求，查询交易状态");
		}
		return new ModelAndView("/return_result", model);
	}
}
